package piwan;

import java.io.IOException;
import java.util.Collection;
import java.util.Scanner;

public class Region {
	public boolean isCapital() { return type.isCapital(); }
	public boolean isOwnedBy( Player p ) { return owner == p; }
	public boolean isOwned() { return owner!=null; }
	public boolean contains( Vector2 pt ) {
		for(Polygon p: polys)
			if( p.contains(pt) ) return true;
		return false;
	}
	public void resetExtraDefense() { extra = type.getDefenseBonus(); }
	public boolean damage() {
		assert(solds>0);
		if( extra > 0 )
			--extra;
		else
			--solds;
		
		if(solds==0)
			return true;
		else
			return false;
	}
	
	public void				setType(RegionType t) { type = t; }
	public void				setOwner(Player pl) { owner = pl; }
	public void				setId( int newId ) { id = newId; }
	public void				setSoldiers(int i) { solds = i; }
	public void				setExtraDefense(int i) { extra = i; }
	public void				addSoldiers(int i) { solds += i; }
	public void				addAdjacent(Collection<Region> from) {
		for(Region r: adjs)
			from.add(r);
		adjs = new Region[from.size()];
		int i=0;
		for(Region r: from)
			adjs[i++] = r;
	}
	public Player			getOwner() { return owner; }
	public int				getId() { return id; }
	public RegionType		getType() { return type; }
	public ResourceType[]	getResources() { return rscs; }
	public Polygon[]		getPolygons() { return polys; }
	public String			getName() { return name; }
	public Region[]			getAdjacent() { return adjs; }
	public int				getSoldiers() { return solds; }
	public int				getExtraDefense() { return extra; }
	public int				getTotalDefense() { return extra + solds; }
	public Polygon			getMainPolygon() { return mpoly; }
	public Vector2			getHotspot() { return hot; }
	public boolean			isAdjacentTo(Region to) {
		for(Region adj: adjs)
			if( to == adj )
				return true;
		return false;
	}
	
	
	public void readFromMap( Scanner file, World w ) throws IOException {
		name = file.next().replace('_', ' ');
		Polygon p = new Polygon();
		p.readFromMap(file,w);
		polys	= p.breakIslands();
		mpoly	= polys[0];
		hot		= mpoly.getCentroid();
		int x = file.nextInt();
		if(x==-1)
			type	= w.getRegionType(0);
		else
			type	= w.getRegionType(x);
		 
		int nrscs = file.nextInt();
		rscs = new ResourceType[nrscs];
		for(int i=0; i<nrscs; ++i)
			rscs[i] = w.getResourceType(file.nextInt());
		int nadj = file.nextInt();
		
		adjs = new Region[nadj];
		for(int i=0; i<nadj; ++i) {
			x = file.nextInt();
			assert(x<w.getRegionCount()) : name;
			adjs[i] = w.getRegion(x);
		}
	}
	
	private int				id		= -1;
	private Player			owner	= null;
	private RegionType		type	= null;
	private ResourceType[]	rscs	= null;
	private String			name	= null;
	private Polygon[]		polys	= null;
	private Region[]		adjs	= null;
	private Vector2			hot		= null;
	private Polygon			mpoly	= null;
	private int				extra	= 0;
	private int				solds	= 0;
	
}
